<?if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
 * Planet Ilkom-ub
 *
 * Planet Ilkom-ub
 *
 * @package		Model Posting
 * @author		Ibnoe Daqiqil Id
 * @copyright	Copyright (c) 2008, www.ibnoe.web.id.
 * @link		http://www.ibnoe.web.id
 * @since		Version 1.0
 * @datetime    18-3-2008 12:33
 */
 
class mdl_posts extends Model {

	var $id;
	var $site_id;
	var $date;
	var $title;
	var $content;
	var $url;


	var $page_num;
	var $limit;
	var $numpages;
	var $paginate;
	var $numrows;
	


	function mdl_posts() 
	{
		parent::Model();
		$this->limit = 20;
	}
	
	function get() 
	{
		/**
		 * Prepare the query
		 */
		$this->_prep_query();
		$query = $this->db->get("posts");
		$this->numrows=$query->num_rows;
		$this->numpages = ceil($query->num_rows / $this->limit);

		$offset = ($this->page_num * $this->limit) - $this->limit;
		$this->db->limit($this->limit, $this->page_num );

		$this->_prep_query();
		$query = $this->db->get("posts");
		
		/**
		 * is single or multi record? 
		 */
		// vardump($this->db->last_query());
		if ($this->id) 
		{
			$result = $query->row();
			if ($result) 
				return ($result);
			else 			
				return (FALSE);
		}
		else 
		{
			$results = $query->result();
			if ($results) 
				return ($results);
			else 
				return (FALSE);
		}

	}

	function save() 
	{
		$dbArray = array(
			"site_id"		=>	$this->site_id,
			"title"			=>	$this->title,
			"content"		=>	$this->content,
			"date"			=>	$this->date,
			"url"			=>	$this->url);

	
		if ($this->id) 
		{
			$this->db->where("id", $this->id);
			$this->db->update("posts", $dbArray);
		}

		else 
		{
			$this->db->where("posts.url", $this->url);
			$query = $this->db->get("posts");
			
			if ($query->result_array())
			{
				$this->db->where("url", $this->url);
				$this->db->update("posts", $dbArray);
			}
			else
				$this->db->insert("posts", $dbArray);
			//$this->id = $this->db->insert_id();
		}

	}

	function delete() {

		$this->db->where("id", $this->id);
		$this->db->delete("posts");

	}


	function _prep_query() {
		$this->db->select("
			posts.id AS id,
			DATE_FORMAT(posts.date, '%m/%d/%Y at %h:%i %p') AS date,
			posts.title AS title,
			posts.content AS content,
			posts.url AS url,
			site.site_url AS site_url,
			site.name AS site_name
		");

		// create the joins
		$this->db->join("site", "site.site_id = posts.site_id");
		
		if ($this->id) 
		{
			$this->db->where("posts.id", $this->post_id);
		}

		if ($this->site_id) 
		{
			$this->db->where("site.site_id", $this->site_id);
		}
		
	
		$this->db->orderby("posts.date DESC");

	}

	

}

?>